<?php
/**
 * Created by Benjamin.
 * Date: 2020/5/8
 * Time: 14:52
 */

namespace App\Model;


use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\DbManager;

class GroupModel  extends AbstractModel
{
    protected $tableName = 'group_lists';
    protected $primaryKey = 'id';
    const STATUS_DEL = 0;#删除
    const STATUS_NORMAL = 1;#正常

    /**创建群
     * @param $userId创建人用户id
     * @param $groupName群名
     * @param $userIdArr群成员id
     */
    function createGroup($userId,$userIdArr){
        try{
            //开启事务
            DbManager::getInstance()->startTransaction();
            //创建群
           $groupId =  self::create()->data([
                'user_id' => $userId,
                'created_at'  => date("Y-m-d H:i:s"),
                'updated_at'  => date("Y-m-d H:i:s"),
            ], false)->save();
            //加入群聊
            foreach ($userIdArr as $id){
             UserGroupModel::create()->data([
                   'user_id'=>$id,
                   'group_id'=>$groupId,
                   'created_at'  => date("Y-m-d H:i:s"),
                   'updated_at'  => date("Y-m-d H:i:s"),
               ])->save();
             unset($id);
            }
            unset($userIdArr);
        } catch(\Throwable  $e){
            //回滚事务
            unset($groupId);
            DbManager::getInstance()->rollback();
            return false;
        } finally {
            //提交事务
            DbManager::getInstance()->commit();
        }
        unset($groupId);
        return true;
    }
}